import asyncio
import os

import socketio
import uvicorn
import uuid

from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
from starlette.staticfiles import StaticFiles

from common.GlobalConfig import config
from modules.http_resp import ResponseSuccess

from controller.login import router as log_router
from controller.user import router as user_router
from controller.friend import router as friend_router
from controller.dialog import router as dialog_router
from controller.group import router as group_router
from controller.chatting import router as chatting_router
from controller.message import router as message_router

from websocket.EventsGateway import EventsGateway, MyCustomNamespace

app = FastAPI(debug=True)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 允许的源列表
    allow_credentials=True,  # 支持凭证（例如cookies）
    allow_methods=["*"],  # 允许所有HTTP方法
    allow_headers=["*"],  # 允许所有头部
)

# 初始化服务实例
# 创建一个 Socket.IO 服务器实例
sio = socketio.AsyncServer(
    async_mode='asgi',
    cors_allowed_origins='*',  # 开发环境开放所有跨域
    engineio_logger=True,  # 开启日志以便调试
    logger=True,
    engineio_version=3  # 支持 EIO=3 的客户端
)

# 将 Socket.IO 服务器附加到 FastAPI 应用
socket_app = socketio.ASGIApp(sio, other_asgi_app=app, socketio_path='socket.io')

if not os.path.exists(config.SAVE_FILE_PATH):
    os.makedirs(config.SAVE_FILE_PATH, exist_ok=True)

app.mount(f"/static", StaticFiles(directory="static"), name="static")

# 初始化网关类
gateway = EventsGateway(sio)


@app.post("/upload")
async def uploadFile(file: UploadFile = File(...)):
    # 读取文件内容（如果需要）
    contents = await file.read()
    fileName = f"{uuid.uuid4()}.{file.filename.split('.')[-1]}"

    # 这里可以进行保存文件、处理文件等操作
    with open(f"{config.SAVE_FILE_PATH}/{fileName}", "wb") as f:
        f.write(contents)
    return ResponseSuccess({"fileUrl": f"{config.SERVER_HOST}/{config.SAVE_FILE_PATH}/{fileName}", "fileType": file.content_type})


app.include_router(log_router, prefix='/login')
app.include_router(user_router, prefix='/user')
app.include_router(friend_router, prefix='/friends')
app.include_router(dialog_router, prefix='/dialog')
app.include_router(chatting_router, prefix='/chatting')
app.include_router(group_router, prefix='/group')
app.include_router(message_router, prefix='/message')

if __name__ == '__main__':
    # 启动socket通信
    # asyncio.run(start())
    # 启动http server
    uvicorn.run(socket_app, host='0.0.0.0', port=8000)
